<template>
<div class="content" id="content">
  <lq-form :form="form"  ref="formRef">
<!--    <template #header>
      <div class="form-title">重在危险源信息</div>
    </template>-->
    <template #footer>
      <div>
          <el-button type="primary" @click="query">查询</el-button>
          <el-button type="success" @click="()=>{
            dialog.visible = true;
            optCase.operaCase = 'add';
            optCase.id = '';
            optCase.hazardInfoId='';
            optCase.hazardCode='';
          }">
            新增
          </el-button>
          <el-button type="warning" @click="handleExport">导出</el-button>
          <el-button type="danger" @click="lqtableCommon.handleRemove(selections, handleRemove)">批量删除</el-button>
      </div>
    </template>
  </lq-form>
  <br>
  <!-- 表格区 -->
  <div class="table" id="tableRegion">
    <lq-table ref="tableRef"
              :columns="columns"
              :records="tableData.records"
              size="default"
              :border="true"
              :header-cell-style="{background:'#e1eaf6', color:'#333333'}"
              :stripe="true"
              :pagination="paginationProps"
              @on-selections="handleSelections"
              @on-pagination="handlePagination"
    >
      <template #operate="scope">
        <el-button @click="handleEdit(scope.row)" type="primary">编辑</el-button>
        <el-button @click="() => {
                      isDeleteBatch = false;
                      delId = [scope.row.id];
                      lqtableCommon.handleRemove([scope.row.id], handleRemove);
                   }"
                  type="danger">删除
        </el-button>
      </template>
    </lq-table>
  </div>
  <el-dialog v-model="dialog.visible"
             v-bind="{...dialog.innerAttrs}"
             v-on="dialog.events">
    <index-tabs ref="indexTabsRef"
                @changeTitle="( {title} )=>{ dialog.innerAttrs.title = title; }"
    >
    </index-tabs>
  </el-dialog>
</div>
</template>

<script setup lang="ts">
/**
 * 全局方法引入
 */
const global = getCurrentInstance().appContext.config.globalProperties;

import {
  ref,
  reactive,
  onMounted,
  toValue,
  getCurrentInstance,
  provide,
} from "vue";
import {FormInstance, FormRules} from "element-plus";

import { ElMessage, ElMessageBox } from "element-plus";
import lqtableCommon from '../../components/lqtableCommon.js';
import {closeDialogKey, editKey} from '../../components/keys.js';
import commonConst from "@/config/const";
import LqForm from "@/pages/components/LqForm.vue";
import LqTable from '@/pages/components/LqTable.vue'
import IndexTabs from '@/pages/ent/majorHazard/IndexTabs.vue'


// 示例数据结构
const form = ref({
  innerAttrs: {
    labelPosition:'right',
    labelWidth: 110,
  },
  model: {
    name: '',
    level: '',
    submitDates: [],
    validityDates: [],
    birthday: ''
  },
  formItems: [
    { type: 'input', label: '重大危险源名称: ', prop: 'name', span: 5, maxlength: 30, placeholder:'重大危险源名称' },
    { type: 'select', label: '重大危险源级别: ', prop: 'level', options: commonConst.majorHazardLevelList, span: 5, placeholder:'请选择重大危险源级别' },
    { type: 'daterange', label: '备案日期: ', prop: 'submitDates', valueFormat: 'YYYY-MM-DD', span: 7 },
    { type: 'daterange', label: '有效期: ', prop: 'validityDates', span: 7 },
  ],
  buttonsAttrs: {
    align: 'left'
  }
});

// 表单验证规则
const rules = reactive<FormRules>({});

// 表单验证规则
const formRef = ref<FormInstance>();

const handleSubmit = async () => {
  const valid = await formRef.value?.validateForm();
  console.log(valid); //true or false
}

const handleReset = () => {
  formRef.value?.resetFields();
}

//================ dialog ============
const indexTabsRef = ref();

const dialog = ref({
  visible: false,
  innerAttrs: {
    id: 'majorHazardBaseInfoDialog',
    class: 'majorHazardBaseInfoDialog',
    title: '重大危险源信息',
    width: "80%",
    top: '1vh',
    destroyOnClose: true,
  },
  events: {
    open: () => {
      console.log('dialog open.....');
      // console.log(toValue(tableData.value));
    },
    close: () => {
      console.log('dialog close.....');
      //关闭对话框时重置回第一个标签页
      indexTabsRef.value?.resetFirstTab();
      indexTabsRef.value?.handleReset();
      optCase.value = {operaCase: '', id: '', hazardInfoId: '', hazardCode: ''}; //清除id
      if (optCase.value.optStatus) query();
    },
  }
})
//关闭对话框
const closeDialog = () => dialog.value.visible = false;
provide(closeDialogKey,closeDialog)

//================ table、分页 =============
const columns = [
  { label: '', type: "selection", width: 40},
  { label: '序号', type: "index", width: 50},
  { label: '重大危险源名称', prop: 'name', type: 'link', minWidth: 200, event: {
      click: (row)=> {
        view(row)
      }
    }
  },
  { label: '备案申请类型', prop: 'applicationType', minWidth: 200},
  { label: "危险物数量", prop: 'materialCount', minWidth: 80 },
  { label: '重大危险源级别', prop: 'level', minWidth: 120},
  { label: "详细地址", prop: 'address', minWidth: 250},
  { label: "重大危险源状态", prop: 'status', minWidth: 110},
  { label: "备案日期", prop: 'submitDate', minWidth: 100},
  { label: "有效期", prop: 'validityDate', minWidth: 100},
  { label: "审核状态", prop: 'registerRecResult', minWidth: 100},
  { label: '操作', prop: 'id', slotName: 'operate', slotted: true, align: 'center', fixed: 'right', minWidth: 150},
]

const tableRef = ref();

const tableData = ref({
  records: [],
  pageSize: 10,
  tableSize: 'default',
  border: true,
});

//分页信息
const paginationProps = reactive({
  pageSize: tableData.value.pageSize,
  pageSizes: [5,10,20,50,100],
  total: 0,
  pageNum: 1,
  small: false,
  paginationAlign:'right',
});

//选择的记录集
const selections = ref([]);

//分页时使用查询参数
const copyFormData = ref({});

//是否显示新增、编辑按钮栏, 查看不显示
const optCase = ref({
  operaCase: 'add',
  id: '',
  hazardInfoId: '',
  hazardCode: '',
  optStatus: false,
});
provide(editKey, optCase);

//删除
const isDeleteBatch = ref(false);
const delId = ref([]);

//=================query and load ==============
//查询
const query = () => {
  // console.log('查询表单：%o', form.value.model);
  copyFormData.value = Object.assign({}, form.value.model);
  //重置分页状态
  resetPagination();
  loadData(1, tableData.value.pageSize);
}

const loadData = (pageNum=1, pageSize=10) => {
  // console.log('加载数据参数：%o', copyFormData.value);
  tableRef.value?.startLoading();

  let obj = global.$delUndefined(copyFormData.value);
  global.$api.getMajorHazardBasicInfoPageList(Object.assign({},obj, {"pageNum": pageNum, "pageSize": pageSize}))
    .then(({ data }) => {
        tableRef.value?.stopLoading();
        if (data.status === 'OK') {
          tableData.value.records = data.data.list;
          paginationProps.total = data.data.total;
        }
    });
};

//=========== 打开编辑画面 ===========
const handleEdit = (row) => {
  optCase.value.operaCase = 'edit';
  optCase.value.id = row.id;
  optCase.value.hazardInfoId = row.id;
  optCase.value.hazardCode = row.hazardCode;
  dialog.value.visible = true;
  console.log(`编辑 ID: %s  Hazard Code: %s`, row.id, row.hazardCode);
};

//=========== 打开查看画面 ===========
const view = (row) => {
  console.log(`查看 ID: %s  Hazard Code: %s`, row.id, row.hazardCode);
  optCase.value.operaCase = 'view';
  optCase.value.id = row.id;
  optCase.value.hazardInfoId = row.id;
  optCase.value.hazardCode = row.hazardCode;
  dialog.value.visible = true;
}

//=========== 删除 ===========
const handleRemove = () => {
  // console.log('批量删除, ID(s): ', toValue(selections));
  // console.log('删除操作, ID: ', toValue(delId));

  global.$api.deleteMajorHazardBasicInfoByIds({
    ids: (isDeleteBatch.value ? selections.value : delId.value),

  }).then( ({data}) => {
    ElMessage({type: "success", message: "您已经成功删除所选记录！"});
    query();
  }).catch((err) => {
    ElMessage({type: "error", message: "服务器端错误删除记录失败！"});
  });
};


// --------------导出功能--------------------------
/**
 * --------------定义Excel头部--------------------------
 */
let tHeader = [
  {name: '备案申请类型', key: 'applicationType'},
  {name: '危险物数量', key: 'materialCount'},
  {name: "重大危险源级别", key: 'level'},
  {name: '详细地址', key: 'address'},
  {name: "重大危险源状态", key: 'status'},
  {name: "备案日期", key: 'submitDate'},
  {name: "有效期", key: 'validityDate'},
  {name: "审核状态", key: 'registerRecResult'},
];


/**
 */
const handleExport = () => {
  let data = Object.assign({}, copyFormData.value.model, {});
  let obj = global.$delUndefined(data);

  global.$api.exportMajorHazardBasicInfoExcel(obj).then(({data}) => {
    if (data.status === 'OK') {
      let exportData = data.data;
      let excelObject = {
        fileName: "企业事故事件信息", //文件名
        tHeader: tHeader, //生成Excel表格的头部标题栏
        excelData: exportData, //需要导出Excel的数据集合
      };
      global.$exportExcel.exportExcel(excelObject);

    }
  });
}

//============================ Copy =================================
//多选回调
const handleSelections = (items) => {
  isDeleteBatch.value = true;
  selections.value = items.value.map((item) => item.id);
  // console.log('选择的ID:',...toValue(selections));
}

//重置分页属性
const resetPagination = () => {
  paginationProps.pageNum = 1;
  paginationProps.pageSize = tableData.value.pageSize;
  paginationProps.total = 0;
};

//分页回调
const handlePagination = ({pageNum, pageSize=10}) => {
  // console.log('分页查询: pageNum=%d, pageSize=%d',pageNum, pageSize);
  loadData(pageNum, pageSize);
}

</script>

<style lang="sass">
.majorHazardBaseInfoDialog .el-dialog__body
  padding: 0px 10px 0px 0px

</style>
